package File;

import java.io.File;
import java.io.IOException;

import jxl.Workbook;
import jxl.write.Label;
import jxl.write.Number;
import jxl.write.NumberFormats;
import jxl.write.WritableCellFormat;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;
import jxl.write.biff.RowsExceededException;

public class FileHandler {
    public static WritableWorkbook workBook;
    public static WritableSheet sheet;
    public static int sheetId = 0;
    public static int lableId = 0;
    public static WritableCellFormat floatFormat;

    /**
     * 
     * @param fileName
     */
    public static void openFile(String fileName) {
	lableId = 0;
	boolean openedFile = true;
	while (openedFile) {
	    try {
		workBook = Workbook.createWorkbook(new File(fileName + ".xls"));
		openedFile = false;
	    } catch (IOException e) {
		System.out.println("cant open file re enter file name");
		openedFile = true;
	    }
	}
	floatFormat = new WritableCellFormat(NumberFormats.FLOAT);
    }

    /**
     * 
     * @param sheetName
     */
    public static void openNewSheet(String sheetName) {
	sheet = workBook.createSheet(sheetName, sheetId);
	sheetId++;
    }

    /**
     * 
     * @param labelName
     */
    public static void addNewLable(String labelName) {
	Label label = new Label(lableId, 0, labelName);
	lableId++;
	try {
	    sheet.addCell(label);
	} catch (RowsExceededException e) {
	    System.out.println("RowsExceededException Fail to write ..");
	    e.printStackTrace();
	    System.exit(-1);
	} catch (WriteException e) {
	    System.out.println("RowsExceededException Fail to write ..");
	    e.printStackTrace();
	    System.exit(-1);
	}

    }

    /**
     * 
     * @param col
     * @param row
     * @param value
     */
    public static void addNewFloatValue(int col, int row, double value) {
	Number number = new Number(col, row, value);
	try {
	    sheet.addCell(number);
	} catch (RowsExceededException e) {
	    // TODO Auto-generated catch block
	    e.printStackTrace();
	} catch (WriteException e) {
	    System.out.println("cant write to file... will exit now ");
	    e.printStackTrace();
	    System.exit(-1);
	}
    }

    public static void closeFile() {
	try {
	    workBook.write();
	} catch (IOException e) {
	    System.out.println("cant write to file .");
	    e.printStackTrace();
	    System.exit(-1);
	}
	try {
	    workBook.close();
	} catch (WriteException e) {
	    System.out.println("cant write to file .");
	    e.printStackTrace();
	    System.exit(-1);
	    e.printStackTrace();
	} catch (IOException e) {
	    System.out.println("cant close file .");
	    e.printStackTrace();
	    System.exit(-1);
	}
    }

}
